// 数据服务 - 统一处理真实API和虚拟数据的切换
import { useMockData } from '@/config/app.js'
import { getMockData, mockApiResponse, mockApiDelay, generateId, formatDate } from './mockData.js'
import {
  dashboardAPI,
  clientsAPI,
  configAPI,
  alertsAPI,
  behaviorAPI,
  filesAPI,
  internetControlAPI,
  appTrafficAPI,
  usersAPI,
  departmentsAPI,
  controlAPI
} from './api.js'

// 仪表板数据服务
export const dashboardService = {
  // 获取仪表板统计数据
  async getStats() {
    if (useMockData()) {
      // 返回虚拟数据
      return await mockApiResponse({
        online_clients: 15,
        total_clients: 20,
        warning_clients: 2,
        system_uptime: 86400
      })
    } else {
      // 调用真实API
      return dashboardAPI.getStats()
    }
  },

  // 获取行为趋势数据
  async getBehaviorTrends(params = {}) {
    if (useMockData()) {
      // 根据时间范围生成不同的数据
      const generateTimeLabels = (timeRange, startDate, endDate, startWeek, endWeek) => {
        // 如果有自定义日期范围，生成对应的标签
        if (timeRange === 'day' && startDate && endDate) {
          const start = new Date(startDate)
          const end = new Date(endDate)
          const labels = []
          const current = new Date(start)
          while (current <= end) {
            labels.push(current.toISOString().split('T')[0])
            current.setDate(current.getDate() + 1)
          }
          return labels.length > 10 ? labels.slice(0, 10) : labels // 限制显示数量
        }

        if (timeRange === 'week' && startWeek && endWeek) {
          // 简化处理，返回周标签
          return ["第1周", "第2周", "第3周", "第4周", "第5周"]
        }

        switch (timeRange) {
          case 'day':
            return ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00"]
          case 'week':
            return ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
          case 'month':
            return ["第1周", "第2周", "第3周", "第4周"]
          default:
            return ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00"]
        }
      }

      const generateMockData = (timeLabels, baseValues, variation = 50) => {
        return timeLabels.map((time, index) => {
          const count = Math.max(0, baseValues[index] + Math.random() * variation - variation/2)
          // Y坐标计算：将count值映射到SVG坐标系（0-140像素）
          // 最大值500对应y=20，最小值0对应y=140
          const y = 140 - (count / 500) * 120 + 20
          return {
            time,
            count: Math.round(count), // 显示整数
            y: Math.max(20, Math.min(140, y)) // 限制在合理范围内
          }
        })
      }

      const timeLabels = generateTimeLabels(params.timeRange, params.startDate, params.endDate, params.startWeek, params.endWeek)
      const baseKeyboardValues = [300, 420, 380, 320, 350, 450, 410, 480, 430, 460]
      const baseCompareValues = [280, 380, 360, 300, 330, 420, 390, 450, 410, 440]

      // 修复对比数据生成逻辑 - 确保在对比模式下总是生成对比数据
      let compareData = null
      if (params.compareMode === 'compare') {
        // 两人对比模式：生成第二个用户的数据
        compareData = generateMockData(timeLabels, baseCompareValues)
      } else if (params.compareMode === 'vs_dept') {
        // 个人vs部门模式：生成部门平均数据
        const deptBaseValues = [320, 400, 370, 310, 340, 430, 400, 460, 420, 450]
        compareData = generateMockData(timeLabels, deptBaseValues)
      }

      const mockData = {
        keyboard: generateMockData(timeLabels, baseKeyboardValues),
        mouse: generateMockData(timeLabels, [180, 220, 200, 190, 190, 250, 230, 270, 240, 260]),
        compare: compareData,
        // 添加用户和部门信息用于显示
        selectedUser: params.selectedUser,
        user1: params.user1,
        user2: params.user2,
        selectedDept: params.selectedDept,
        compareMode: params.compareMode
      }
      return await mockApiResponse(mockData)
    } else {
      // 调用真实API
      return dashboardAPI.getBehaviorTrends(params)
    }
  },

  // 获取最新预警列表
  async getRecentAlerts(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = [
        {
          id: 1,
          type: "traffic",
          clientName: "研发部-张三",
          severity: 3,
          description: "流量使用超限（1204/1024 MB）",
          createdAt: "2025-07-24 13:45:00"
        },
        {
          id: 2,
          type: "offline",
          clientName: "监控点C3",
          severity: 2,
          description: "检测到异常行为",
          createdAt: "2025-07-24 13:30:00"
        },
        {
          id: 3,
          type: "security",
          clientName: "市场部-李四",
          severity: 4,
          description: "访问被禁网站：facebook.com",
          createdAt: "2025-07-24 13:15:00"
        }
      ]
      return await mockApiResponse(mockData)
    } else {
      // 调用真实API
      return dashboardAPI.getRecentAlerts(params)
    }
  },

  // 获取鼠标趋势数据（原热力图改为趋势图）
  async getMouseHeatmap(params = {}) {
    if (useMockData()) {
      // 根据时间范围生成不同的数据
      const generateTimeLabels = (timeRange, startDate, endDate, startWeek, endWeek) => {
        // 如果有自定义日期范围，生成对应的标签
        if (timeRange === 'day' && startDate && endDate) {
          const start = new Date(startDate)
          const end = new Date(endDate)
          const labels = []
          const current = new Date(start)
          while (current <= end) {
            labels.push(current.toISOString().split('T')[0])
            current.setDate(current.getDate() + 1)
          }
          return labels.length > 10 ? labels.slice(0, 10) : labels // 限制显示数量
        }

        if (timeRange === 'week' && startWeek && endWeek) {
          // 简化处理，返回周标签
          return ["第1周", "第2周", "第3周", "第4周", "第5周"]
        }

        switch (timeRange) {
          case 'day':
            return ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00"]
          case 'week':
            return ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
          case 'month':
            return ["第1周", "第2周", "第3周", "第4周"]
          default:
            return ["09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00"]
        }
      }

      const generateTrendData = (timeLabels, baseValues, variation = 30) => {
        return timeLabels.map((time, index) => {
          const count = Math.max(0, baseValues[index] + Math.random() * variation - variation/2)
          // Y坐标计算：将count值映射到SVG坐标系
          // 鼠标事件通常比键盘事件少，最大值300对应y=20，最小值0对应y=140
          const y = 140 - (count / 300) * 120 + 20
          return {
            time,
            count: Math.round(count), // 显示整数
            y: Math.max(20, Math.min(140, y)) // 限制在合理范围内
          }
        })
      }

      const timeLabels = generateTimeLabels(params.timeRange, params.startDate, params.endDate, params.startWeek, params.endWeek)
      const baseMouseValues = [180, 220, 200, 190, 190, 250, 230, 270, 240, 260]

      // 修复对比数据生成逻辑 - 确保在对比模式下总是生成对比数据
      let compareData = null
      if (params.compareMode === 'compare') {
        // 两人对比模式：生成第二个用户的数据
        const compareBaseValues = [160, 200, 180, 170, 170, 230, 210, 250, 220, 240]
        compareData = generateTrendData(timeLabels, compareBaseValues)
      } else if (params.compareMode === 'vs_dept') {
        // 个人vs部门模式：生成部门平均数据
        const deptBaseValues = [170, 210, 190, 180, 180, 240, 220, 260, 230, 250]
        compareData = generateTrendData(timeLabels, deptBaseValues)
      }

      const mouseTrendData = generateTrendData(timeLabels, baseMouseValues)

      const mockData = {
        mouse: mouseTrendData,
        compare: compareData,
        maxActivity: Math.max(...mouseTrendData.map(d => d.count)),
        avgActivity: Math.round(mouseTrendData.reduce((sum, d) => sum + d.count, 0) / mouseTrendData.length),
        // 添加用户和部门信息用于显示
        selectedUser: params.selectedUser,
        user1: params.user1,
        user2: params.user2,
        selectedDept: params.selectedDept,
        compareMode: params.compareMode
      }
      return await mockApiResponse(mockData)
    } else {
      // 调用真实API
      return dashboardAPI.getMouseHeatmap(params)
    }
  }
}

// 客户端数据服务
export const clientsService = {
  // 获取客户端列表
  async getClients(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        list: [
          {
            id: 'client-001',
            name: "张三的电脑",
            ip: "127.0.0.1",
            status: "online",
            last_online: "2025-07-24T17:15:29+08:00",
            department: "前端组",
            dept_id: 3,
            user: "张三",
            mac_address: "00:11:22:33:44:55",
            hostname: "PC-ZHANGSAN",
            os_info: "Windows 10 Pro",
            last_heartbeat: "2025-07-25T17:19:29+08:00",
            lastHeartbeat: "2025-07-25T17:19:29+08:00",
            description: "张三的工作电脑",
            websocket_url: "ws://127.0.0.1:8090/ws",
            websocket_port: 8090,
            service_status: "active"
          },
          {
            id: 'client-002',
            name: "李四的电脑",
            ip: "127.0.0.1",
            status: "online",
            last_online: "2025-07-24T16:30:15+08:00",
            department: "后端组",
            dept_id: 4,
            user: "李四",
            mac_address: "00:11:22:33:44:66",
            hostname: "PC-LISI",
            os_info: "Windows 11 Pro",
            last_heartbeat: "2025-07-25T16:30:15+08:00",
            lastHeartbeat: "2025-07-25T16:30:15+08:00",
            description: "李四的开发电脑",
            websocket_url: "ws://127.0.0.1:8090/ws",
            websocket_port: 8090,
            service_status: "active"
          },
          {
            id: 'client-003',
            name: "王五的电脑",
            ip: "127.0.0.1",
            status: "offline",
            last_online: "2025-07-24T17:10:45+08:00",
            department: "测试组",
            dept_id: 1,
            user: "王五",
            mac_address: "00:11:22:33:44:77",
            hostname: "PC-WANGWU",
            os_info: "Windows 10 Pro",
            last_heartbeat: "2025-07-25T17:18:45+08:00",
            lastHeartbeat: "2025-07-25T17:18:45+08:00",
            description: "王五的测试电脑",
            websocket_url: "",
            websocket_port: 0,
            service_status: "inactive"
          }
        ],
        total: 3
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return clientsAPI.getClients(params)
    }
  },

  // 获取客户端详情
  async getClient(clientId) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        id: clientId,
        name: "张三的电脑",
        ip: "192.168.1.100",
        status: "online",
        last_online: "2025-07-24T17:15:29+08:00",
        department: "前端组",
        user: "张三",
        mac_address: "00:11:22:33:44:55",
        hostname: "PC-ZHANGSAN",
        os_info: "Windows 10 Pro",
        last_heartbeat: "2025-07-24T17:19:29+08:00"
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return clientsAPI.getClient(clientId)
    }
  },

  // 更新客户端信息
  async updateClient(clientId, data) {
    if (useMockData()) {
      // 模拟更新成功
      return mockApiResponse({ message: "Client updated successfully" })
    } else {
      // 调用真实API
      return clientsAPI.updateClient(clientId, data)
    }
  },

  // 添加客户端
  async addClient(data) {
    if (useMockData()) {
      // 模拟添加成功
      return mockApiResponse({
        message: "Client added successfully",
        data: {
          id: data.id,
          ...data,
          status: 'offline',
          lastHeartbeat: new Date().toISOString()
        }
      })
    } else {
      // 调用真实API
      return clientsAPI.registerClient(data)
    }
  },

  // 删除客户端
  async deleteClient(clientId) {
    if (useMockData()) {
      // 模拟删除成功
      return mockApiResponse({ message: "Client deleted successfully" })
    } else {
      // 调用真实API
      return clientsAPI.deleteClient(clientId)
    }
  }
}

// 配置管理数据服务
export const configService = {
  // 获取配置列表
  async getConfigs(params = {}) {
    if (useMockData()) {
      // 返回更丰富的虚拟数据
      const allMockConfigs = [
        {
          id: 1,
          name: "全局默认配置",
          type: "global",
          target_id: 0,
          targetId: 0,
          description: "系统默认全局配置，适用于所有客户端",
          priority: 30,
          enabled: true,
          version: 1,
          updated_at: "2025-07-24 16:24:50",
          updatedAt: "2025-07-24 16:24:50",
          settings: {
            usbPolicy: "allow",
            usbWhitelist: "",
            wifiPolicy: "allow",
            wifiWhitelist: "",
            enableTrafficControl: false,
            dailyTrafficLimit: 2048,
            weeklyTrafficLimit: 10240,
            monthlyTrafficLimit: 40960,
            domainBlacklist: "*.game.com\n*.gambling.com",
            ipBlacklist: "",
            softwareBlacklist: "game.exe\nqq.exe",
            offlineTimeout: 5,
            alertLevel: "medium",
            enableKeyboardMouseMonitor: true,
            keyboardMouseSaveInterval: 300
          }
        },
        {
          id: 2,
          name: "研发部配置",
          type: "department",
          target_id: 1,
          targetId: 1,
          description: "研发部门专用配置，允许更多开发工具",
          priority: 60,
          enabled: true,
          version: 2,
          updated_at: "2025-07-24 15:30:20",
          updatedAt: "2025-07-24 15:30:20",
          settings: {
            usbPolicy: "whitelist",
            usbWhitelist: "VID_0781&PID_5567\nKingston DataTraveler",
            wifiPolicy: "allow",
            wifiWhitelist: "",
            enableTrafficControl: true,
            dailyTrafficLimit: 4096,
            weeklyTrafficLimit: 20480,
            monthlyTrafficLimit: 81920,
            domainBlacklist: "*.social.com\n*.entertainment.com",
            ipBlacklist: "203.0.113.0/24",
            softwareBlacklist: "game.exe",
            offlineTimeout: 10,
            alertLevel: "low",
            enableKeyboardMouseMonitor: true,
            keyboardMouseSaveInterval: 600
          }
        },
        {
          id: 3,
          name: "张三个人配置",
          type: "individual",
          target_id: 1,
          targetId: 1,
          description: "张三的个人工作配置",
          priority: 90,
          enabled: true,
          version: 1,
          updated_at: "2025-07-24 14:15:30",
          updatedAt: "2025-07-24 14:15:30",
          settings: {
            usbPolicy: "block",
            usbWhitelist: "",
            wifiPolicy: "whitelist",
            wifiWhitelist: "CompanyWiFi\nGuestWiFi",
            enableTrafficControl: true,
            dailyTrafficLimit: 1024,
            weeklyTrafficLimit: 5120,
            monthlyTrafficLimit: 20480,
            domainBlacklist: "*.social.com\n*.video.com\n*.game.com",
            ipBlacklist: "192.168.100.0/24",
            softwareBlacklist: "game.exe\nqq.exe\nwechat.exe",
            offlineTimeout: 3,
            alertLevel: "high",
            enableKeyboardMouseMonitor: true,
            keyboardMouseSaveInterval: 180
          }
        },
        {
          id: 4,
          name: "李四个人配置",
          type: "individual",
          target_id: 2,
          targetId: 2,
          description: "李四的个人工作配置",
          priority: 90,
          enabled: true,
          version: 1,
          updated_at: "2025-07-24 13:45:15",
          updatedAt: "2025-07-24 13:45:15",
          settings: {
            usbPolicy: "allow",
            usbWhitelist: "",
            wifiPolicy: "allow",
            wifiWhitelist: "",
            enableTrafficControl: false,
            dailyTrafficLimit: 2048,
            weeklyTrafficLimit: 10240,
            monthlyTrafficLimit: 40960,
            domainBlacklist: "",
            ipBlacklist: "",
            softwareBlacklist: "",
            offlineTimeout: 5,
            alertLevel: "medium",
            enableKeyboardMouseMonitor: false,
            keyboardMouseSaveInterval: 300
          }
        },
        {
          id: 5,
          name: "市场部配置",
          type: "department",
          target_id: 3,
          targetId: 3,
          description: "市场部门专用配置，允许社交媒体访问",
          priority: 60,
          enabled: true,
          version: 1,
          updated_at: "2025-07-24 12:20:45",
          updatedAt: "2025-07-24 12:20:45",
          settings: {
            usbPolicy: "whitelist",
            usbWhitelist: "VID_0781&PID_5567",
            wifiPolicy: "allow",
            wifiWhitelist: "",
            enableTrafficControl: true,
            dailyTrafficLimit: 3072,
            weeklyTrafficLimit: 15360,
            monthlyTrafficLimit: 61440,
            domainBlacklist: "*.game.com\n*.gambling.com",
            ipBlacklist: "",
            softwareBlacklist: "game.exe",
            offlineTimeout: 8,
            alertLevel: "medium",
            enableKeyboardMouseMonitor: true,
            keyboardMouseSaveInterval: 450
          }
        }
      ]

      // 根据筛选参数过滤数据
      let filteredConfigs = allMockConfigs

      if (params.type) {
        filteredConfigs = filteredConfigs.filter(config => config.type === params.type)
      }

      if (params.department && params.type === 'department') {
        filteredConfigs = filteredConfigs.filter(config => config.target_id === parseInt(params.department))
      }

      if (params.client && params.type === 'individual') {
        filteredConfigs = filteredConfigs.filter(config => config.target_id === parseInt(params.client))
      }

      const mockData = {
        list: filteredConfigs,
        total: filteredConfigs.length
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      try {
        const response = await configAPI.getConfigs(params)

        // 确保返回的数据格式一致
        if (response && typeof response === 'object') {
          // 如果API直接返回数组
          if (Array.isArray(response)) {
            return {
              success: true,
              list: response,
              total: response.length
            }
          }
          // 如果API返回标准格式
          return response
        }

        // 如果响应格式不正确，返回空结果
        return {
          success: true,
          list: [],
          total: 0
        }
      } catch (error) {
        console.error('真实API调用失败:', error)
        throw error
      }
    }
  },

  // 获取配置详情
  async getConfig(configId) {
    if (useMockData()) {
      // 根据ID返回对应的虚拟数据
      const configMap = {
        1: {
          id: 1,
          name: "全局默认配置",
          type: "global",
          target_id: 0,
          targetId: 0,
          description: "系统默认全局配置，适用于所有客户端",
          settings: {
            usbPolicy: "allow",
            usbWhitelist: "",
            wifiPolicy: "allow",
            wifiWhitelist: "",
            enableTrafficControl: false,
            dailyTrafficLimit: 2048,
            weeklyTrafficLimit: 10240,
            monthlyTrafficLimit: 40960,
            domainBlacklist: "*.game.com\n*.gambling.com",
            ipBlacklist: "",
            softwareBlacklist: "game.exe\nqq.exe",
            offlineTimeout: 5,
            alertLevel: "medium",
            enableKeyboardMouseMonitor: true,
            keyboardMouseSaveInterval: 300
          }
        },
        2: {
          id: 2,
          name: "研发部配置",
          type: "department",
          target_id: 1,
          targetId: 1,
          description: "研发部门专用配置，允许更多开发工具",
          settings: {
            usbPolicy: "whitelist",
            usbWhitelist: "VID_0781&PID_5567\nKingston DataTraveler",
            wifiPolicy: "allow",
            wifiWhitelist: "",
            enableTrafficControl: true,
            dailyTrafficLimit: 4096,
            weeklyTrafficLimit: 20480,
            monthlyTrafficLimit: 81920,
            domainBlacklist: "*.social.com\n*.entertainment.com",
            ipBlacklist: "203.0.113.0/24",
            softwareBlacklist: "game.exe",
            offlineTimeout: 10,
            alertLevel: "low",
            enableKeyboardMouseMonitor: true,
            keyboardMouseSaveInterval: 600
          }
        }
      }

      const mockData = configMap[configId] || configMap[1]
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return configAPI.getConfig(configId)
    }
  },

  // 创建配置
  async createConfig(data) {
    if (useMockData()) {
      // 模拟创建成功，返回新的ID
      const newId = Math.floor(Math.random() * 1000) + 100
      return mockApiResponse({
        id: newId,
        message: "配置创建成功",
        data: {
          ...data,
          id: newId,
          created_at: new Date().toISOString(),
          updated_at: new Date().toISOString()
        }
      })
    } else {
      // 调用真实API
      return configAPI.createConfig(data)
    }
  },

  // 更新配置
  async updateConfig(configId, data) {
    if (useMockData()) {
      // 模拟更新成功
      return mockApiResponse({
        message: "配置更新成功",
        data: {
          ...data,
          id: configId,
          updated_at: new Date().toISOString()
        }
      })
    } else {
      // 调用真实API
      return configAPI.updateConfig(configId, data)
    }
  },

  // 应用配置
  async applyConfig(configId, data) {
    if (useMockData()) {
      // 模拟应用成功
      let appliedCount = 1
      if (data.scope === 'global') {
        appliedCount = 5 // 假设有5个客户端
      } else if (data.scope === 'department') {
        appliedCount = 3 // 假设部门有3个客户端
      } else if (data.client_ids) {
        appliedCount = data.client_ids.length
      }
      return mockApiResponse({
        message: "配置应用成功",
        applied: appliedCount,
        failed: 0,
        details: {
          scope: data.scope,
          target_id: data.target_id,
          applied_at: new Date().toISOString()
        }
      })
    } else {
      // 调用真实API
      return configAPI.applyConfig(configId, data)
    }
  },

  // 删除配置
  async deleteConfig(configId) {
    if (useMockData()) {
      // 模拟删除成功
      return mockApiResponse({
        message: "配置删除成功",
        deleted_id: configId,
        deleted_at: new Date().toISOString()
      })
    } else {
      // 调用真实API
      return configAPI.deleteConfig(configId)
    }
  }
}

// 预警管理数据服务
export const alertsService = {
  // 获取预警列表
  async getAlerts(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        list: [
          {
            id: 1,
            type: "security",
            subtype: "usb_violation",
            client_id: 1,
            client_name: "张三的工作电脑",
            severity: 3,
            title: "USB设备违规",
            description: "检测到未授权的USB设备连接",
            resolved: false,
            created_at: "2025-07-24T16:28:15+08:00"
          },
          {
            id: 2,
            type: "traffic",
            subtype: "limit_exceeded",
            client_id: 2,
            client_name: "李四的电脑",
            severity: 2,
            title: "流量超限",
            description: "日流量使用超过限制",
            resolved: true,
            created_at: "2025-07-24T15:45:30+08:00"
          }
        ],
        total: 2
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return alertsAPI.getAlerts(params)
    }
  },

  // 获取预警详情
  async getAlert(alertId) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        id: alertId,
        type: "security",
        subtype: "usb_violation",
        client_id: 1,
        severity: 3,
        title: "USB设备违规",
        description: "检测到未授权的USB设备连接",
        detail: '{"device_id": "USB001", "device_name": "Unknown USB Device"}',
        resolved: false,
        created_at: "2025-07-24T16:28:15+08:00",
        client: {
          id: 1,
          name: "张三的工作电脑",
          ip_address: "192.168.1.100",
          status: "online"
        }
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return alertsAPI.getAlert(alertId)
    }
  },

  // 解决预警
  async resolveAlert(alertId, data) {
    if (useMockData()) {
      // 模拟解决成功
      return mockApiResponse({ message: "Alert resolved successfully" })
    } else {
      // 调用真实API
      return alertsAPI.resolveAlert(alertId, data)
    }
  },

  // 删除预警
  async deleteAlert(alertId) {
    if (useMockData()) {
      // 模拟删除成功
      return mockApiResponse({ message: "Alert deleted successfully" })
    } else {
      // 调用真实API
      return alertsAPI.deleteAlert(alertId)
    }
  },

  // 批量删除预警
  async batchDeleteAlerts(alertIds) {
    if (useMockData()) {
      // 模拟批量删除成功
      return mockApiResponse({
        message: "Batch delete successful",
        data: { deleted: alertIds.length }
      })
    } else {
      // 调用真实API
      return alertsAPI.batchDeleteAlerts({ alert_ids: alertIds })
    }
  },

  // 标记所有预警为已读
  async markAllAlertsAsRead() {
    if (useMockData()) {
      // 模拟标记成功
      return mockApiResponse({
        message: "All alerts marked as read successfully",
        data: { processed: 10 }
      })
    } else {
      // 调用真实API
      return alertsAPI.markAllAlertsAsRead()
    }
  },

  // 清空所有预警
  async clearAllAlerts() {
    if (useMockData()) {
      // 模拟清空成功
      return mockApiResponse({
        message: "All alerts cleared successfully",
        data: { deleted: 15 }
      })
    } else {
      // 调用真实API
      return alertsAPI.clearAllAlerts()
    }
  },

  // 获取预警统计
  async getAlertStats(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        total: 15,
        resolved: 8,
        unresolved: 7,
        by_type: {
          security: 6,
          traffic: 4,
          offline: 3,
          software: 2
        },
        by_severity: {
          high: 3,
          medium: 7,
          low: 5
        }
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return alertsAPI.getAlertStats(params)
    }
  }
}

// 行为分析数据服务
export const behaviorService = {
  // 获取行为热力图数据
  async getHeatmap(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        hours: [
          { hour: 9, keyboard: 350, mouse: 180 },
          { hour: 10, keyboard: 420, mouse: 220 },
          { hour: 11, keyboard: 380, mouse: 200 },
          { hour: 14, keyboard: 350, mouse: 190 },
          { hour: 15, keyboard: 290, mouse: 160 },
          { hour: 16, keyboard: 310, mouse: 170 }
        ]
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return behaviorAPI.getHeatmap(params)
    }
  },

  // 获取行为对比数据
  async getCompare(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        users: [
          {
            userId: 1,
            userName: "张三的工作电脑",
            avgKeyboard: 320,
            avgMouse: 180,
            efficiency: 85.5
          },
          {
            userId: 2,
            userName: "李四的电脑",
            avgKeyboard: 280,
            avgMouse: 160,
            efficiency: 78.2
          }
        ]
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return behaviorAPI.getCompare(params)
    }
  }
}

// 文件管理数据服务
export const filesService = {
  // 获取录屏列表
  async getRecordings(params = {}) {
    // 直接调用真实API
    return filesAPI.getRecordings(params)
  },

  // 获取截屏列表
  async getScreenshots(params = {}) {
    // 直接调用真实API
    return filesAPI.getScreenshots(params)
  }
}

// 网络管控数据服务
export const networkService = {
  // 获取网络管控策略列表
  async getPolicies(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        list: [
          {
            policyId: 1,
            clientId: "client-001",
            clientName: "研发部-张三",
            clientIp: "192.168.1.101",
            policyLevel: "individual",
            inheritMode: "override",
            priority: 90,
            config: {
              usbPolicy: "whitelist",
              wifiPolicy: "allow",
              enableTrafficControl: true,
              dailyTrafficLimit: 4096,
              domainBlacklist: "*.game.com\n*.social.com",
              softwareBlacklist: "game.exe\nqq.exe",
              enableKeyboardMouseMonitor: true
            },
            updatedAt: "2025-07-24 14:20:00"
          }
        ],
        total: 1
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return internetControlAPI.getWebBlockingRules(params)
    }
  },

  // 获取流量使用统计
  async getTrafficStats(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        upload: 1024000,
        download: 5120000,
        currentSpeed: {
          upload: 1024,
          download: 5120
        },
        history: [
          { time: "14:00", upload: 1024, download: 2048 },
          { time: "15:00", upload: 1200, download: 2400 },
          { time: "16:00", upload: 800, download: 1600 }
        ]
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return appTrafficAPI.getTrafficStats(params)
    }
  },

  // 获取拦截统计
  async getBlockingStats(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = [
        {
          timestamp: "2025-07-24T14:30:00Z",
          type: "domain",
          target: "facebook.com",
          action: "block",
          clientId: "client-001",
          clientName: "研发部-张三"
        },
        {
          timestamp: "2025-07-24T14:25:00Z",
          type: "ip",
          target: "203.0.113.1",
          action: "block",
          clientId: "client-002",
          clientName: "市场部-李四"
        }
      ]
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return internetControlAPI.getBlockingStats(params)
    }
  }
}

// 网络管控特定功能的数据服务
export const internetControlService = {
  // 获取网站拦截规则
  async getWebBlockingRules(clientId) {
    if (useMockData('webBlocking')) {
      return getMockData('webBlocking')
    } else {
      // 调用真实API
      const clientAPI = createClientAPI(clientId)
      return clientAPI.getInternetControlConfig()
    }
  },

  // 配置网站拦截规则
  async configWebBlocking(clientId, config) {
    if (useMockData('webBlocking')) {
      return mockApiResponse({ message: '网站拦截规则配置成功' })
    } else {
      // 调用真实API
      const clientAPI = createClientAPI(clientId)
      return clientAPI.configWebBlocking(config)
    }
  },

  // 获取IP拦截规则
  async getIpBlockingRules(clientId) {
    if (useMockData('ipBlocking')) {
      return getMockData('ipBlocking')
    } else {
      // 调用真实API
      const clientAPI = createClientAPI(clientId)
      return clientAPI.getInternetControlConfig()
    }
  },

  // 配置IP拦截规则
  async configIpBlocking(clientId, config) {
    if (useMockData('ipBlocking')) {
      return mockApiResponse({ message: 'IP拦截规则配置成功' })
    } else {
      // 调用真实API
      const clientAPI = createClientAPI(clientId)
      return clientAPI.configIpBlocking(config)
    }
  },

  // 获取端口拦截规则
  async getPortBlockingRules(clientId) {
    if (useMockData('portBlocking')) {
      return getMockData('portBlocking')
    } else {
      // 调用真实API
      const clientAPI = createClientAPI(clientId)
      return clientAPI.getInternetControlConfig()
    }
  },

  // 配置端口拦截规则
  async configPortBlocking(clientId, config) {
    if (useMockData('portBlocking')) {
      return mockApiResponse({ message: '端口拦截规则配置成功' })
    } else {
      // 调用真实API
      const clientAPI = createClientAPI(clientId)
      return clientAPI.configPortBlocking(config)
    }
  },

  // 获取拦截统计
  async getBlockingStats(clientId) {
    if (useMockData('blockingStats')) {
      return getMockData('blockingStats')
    } else {
      // 调用真实API
      const clientAPI = createClientAPI(clientId)
      return clientAPI.getInternetControlConfig()
    }
  }
}

// 用户管理数据服务
export const usersService = {
  // 获取用户列表
  async getUsers(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        list: [
          {
            id: 1,
            username: "zhangsan",
            name: "张三",
            email: "zhangsan@company.com",
            role: "user",
            status: "active",
            dept_id: 1,
            department: "技术部",
            created_at: "2025-07-24T10:00:00+08:00",
            last_login: "2025-07-24T16:30:00+08:00"
          },
          {
            id: 2,
            username: "lisi",
            name: "李四",
            email: "lisi@company.com",
            role: "admin",
            status: "active",
            dept_id: 2,
            department: "市场部",
            created_at: "2025-07-23T09:00:00+08:00",
            last_login: "2025-07-24T15:45:00+08:00"
          },
          {
            id: 3,
            username: "wangwu",
            name: "王五",
            email: "wangwu@company.com",
            role: "user",
            status: "inactive",
            dept_id: 1,
            department: "技术部",
            created_at: "2025-07-22T14:00:00+08:00",
            last_login: "2025-07-23T18:00:00+08:00"
          }
        ],
        total: 3,
        page: 1,
        size: 10
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return usersAPI.getUsers(params)
    }
  },

  // 获取用户详情
  async getUser(userId) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        id: userId,
        username: "zhangsan",
        name: "张三",
        email: "zhangsan@company.com",
        role: "user",
        status: "active",
        dept_id: 1,
        department: "技术部",
        created_at: "2025-07-24T10:00:00+08:00",
        last_login: "2025-07-24T16:30:00+08:00"
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return usersAPI.getUser(userId)
    }
  },

  // 创建用户
  async createUser(data) {
    if (useMockData()) {
      // 模拟创建成功
      return mockApiResponse({
        id: Math.floor(Math.random() * 1000) + 100,
        message: "User created successfully"
      })
    } else {
      // 调用真实API
      return usersAPI.createUser(data)
    }
  },

  // 更新用户
  async updateUser(userId, data) {
    if (useMockData()) {
      // 模拟更新成功
      return mockApiResponse({ message: "User updated successfully" })
    } else {
      // 调用真实API
      return usersAPI.updateUser(userId, data)
    }
  },

  // 删除用户
  async deleteUser(userId) {
    if (useMockData()) {
      // 模拟删除成功
      return mockApiResponse({ message: "User deleted successfully" })
    } else {
      // 调用真实API
      return usersAPI.deleteUser(userId)
    }
  },

  // 获取用户选项（用于下拉选择）
  async getUserOptions() {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = [
        {
          id: 1,
          name: "张三",
          username: "zhangsan",
          department: "技术部"
        },
        {
          id: 2,
          name: "李四",
          username: "lisi",
          department: "市场部"
        },
        {
          id: 3,
          name: "王五",
          username: "wangwu",
          department: "技术部"
        }
      ]
      return mockApiResponse(mockData)
    } else {
      // 调用真实API获取用户列表，然后转换为选项格式
      const response = await usersAPI.getUsers({ size: 100 }) // 获取更多用户
      if (response.success && response.data && response.data.list) {
        const options = response.data.list.map(user => ({
          id: user.id,
          name: user.name,
          username: user.username,
          department: user.department || user.dept_name || '未分配部门'
        }))
        return mockApiResponse(options)
      }
      return mockApiResponse([])
    }
  }
}

// 部门管理数据服务
export const departmentsService = {
  // 获取部门列表
  async getDepartments(params = {}) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = [
        {
          id: 1,
          name: "技术部",
          parent_id: null,
          level: 1,
          manager_id: 2,
          manager_name: "李四",
          user_count: 15,
          description: "负责技术研发工作",
          created_at: "2025-07-20T10:00:00+08:00",
          children: [
            {
              id: 3,
              name: "前端组",
              parent_id: 1,
              level: 2,
              manager_id: 1,
              manager_name: "张三",
              user_count: 8,
              description: "前端开发团队",
              created_at: "2025-07-20T11:00:00+08:00"
            },
            {
              id: 4,
              name: "后端组",
              parent_id: 1,
              level: 2,
              manager_id: 3,
              manager_name: "王五",
              user_count: 7,
              description: "后端开发团队",
              created_at: "2025-07-20T11:30:00+08:00"
            }
          ]
        },
        {
          id: 2,
          name: "市场部",
          parent_id: null,
          level: 1,
          manager_id: 5,
          manager_name: "赵六",
          user_count: 10,
          description: "负责市场推广工作",
          created_at: "2025-07-20T10:30:00+08:00",
          children: []
        }
      ]
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      try {
        const response = await departmentsAPI.getDepartments(params)
        return response
      } catch (error) {
        console.warn('真实API调用失败，回退到虚拟数据:', error.message)
        // API调用失败时回退到虚拟数据
        const mockData = [
          {
            id: 1,
            name: "总公司",
            children: [
              {
                id: 2,
                name: "研发部",
                children: [
                  { id: 5, name: "前端组" },
                  { id: 6, name: "后端组" }
                ]
              },
              {
                id: 3,
                name: "测试部",
                children: [
                  { id: 7, name: "功能测试组" },
                  { id: 8, name: "自动化测试组" }
                ]
              },
              { id: 4, name: "产品部" }
            ]
          }
        ]
        return { success: true, data: mockData }
      }
    }
  },

  // 获取部门选项（用于下拉选择）
  async getDepartmentOptions() {
    if (useMockData()) {
      // 返回虚拟数据 - 与API返回的部门名称保持一致
      const mockData = [
        {
          id: 1,
          name: "前端组",
          parent_id: null,
          level: 1,
          label: "前端组"
        },
        {
          id: 2,
          name: "后端组",
          parent_id: null,
          level: 1,
          label: "后端组"
        },
        {
          id: 3,
          name: "市场部",
          parent_id: null,
          level: 1,
          label: "市场部"
        }
      ]
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return departmentsAPI.getDepartmentOptions()
    }
  },

  // 获取部门详情
  async getDepartment(deptId) {
    if (useMockData()) {
      // 返回虚拟数据
      const mockData = {
        id: deptId,
        name: "技术部",
        parent_id: null,
        level: 1,
        manager_id: 2,
        manager_name: "李四",
        user_count: 15,
        description: "负责技术研发工作",
        created_at: "2025-07-20T10:00:00+08:00"
      }
      return mockApiResponse(mockData)
    } else {
      // 调用真实API
      return departmentsAPI.getDepartment(deptId)
    }
  },

  // 创建部门
  async createDepartment(data) {
    if (useMockData()) {
      // 模拟创建成功
      return mockApiResponse({
        id: Math.floor(Math.random() * 1000) + 100,
        message: "Department created successfully"
      })
    } else {
      // 调用真实API
      return departmentsAPI.createDepartment(data)
    }
  },

  // 更新部门
  async updateDepartment(deptId, data) {
    if (useMockData()) {
      // 模拟更新成功
      return mockApiResponse({ message: "Department updated successfully" })
    } else {
      // 调用真实API
      return departmentsAPI.updateDepartment(deptId, data)
    }
  },

  // 删除部门
  async deleteDepartment(deptId) {
    if (useMockData()) {
      // 模拟删除成功
      return mockApiResponse({ message: "Department deleted successfully" })
    } else {
      // 调用真实API
      return departmentsAPI.deleteDepartment(deptId)
    }
  }
}








